package com.liangtian.mdm.base.controller;

import com.liangtian.mdm.base.exception.CustomException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * <p>Encoding    :  UTF-8</p>
 * <p>Package Name: com.liangtian.mdm.system.controller </p>
 * <p>Project Name: dm </p>
 * <p>Copyright   :  Copyright(c) 2016 石化盈科信息技术有限责任公司 </p>
 * <p>Created Time: 2016-04-11 11:26</p>
 * <p>Description : 首页控制器</p>
 *
 * @author : Administrator
 * @version :  1.0
 */
@Controller
public class FirstController {

    /**
     * @return
     * @desc 缺省路径跳转
     */
    @RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET)
    public ModelAndView loginView() {
        ModelAndView view = new ModelAndView();
        view.setViewName("login");
        return view;
    }

    /**
     * @param model
     * @param session
     * @return
     * @throws Exception
     * @desc 首页跳转
     */
    @RequestMapping("/first")
    public String first(Model model, HttpSession session) throws Exception {
        //shiro的session中获取activeUser
        Subject subject = SecurityUtils.getSubject();
        //获取身份信息
        Map<String, Object> loginUser = (Map<String, Object>) subject.getPrincipal();
        model.addAttribute("loginUser", loginUser);
        session.setAttribute("loginUser", loginUser);
        return "/first";
    }

    /**
     * @param request
     * @return
     * @throws Exception
     * @desc 用户登录提交方法
     */
    //用户登陆提交方法
    @RequestMapping(value = "/loginUser")
    public String login(HttpServletRequest request) throws Exception {
        //若果登录失败从request中获取异常信息，shiroLoginFailure就是shiro异常类的全限定名
        String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
        if (exceptionClassName != null) {
            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
                throw new CustomException("账号不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
                throw new CustomException("用户名/密码错误");
            } else {
                throw new Exception();
            }
        }
        return "login";
    }
}
